package yelmor.comm100.configure;

import org.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import yelmor.comm100.service.CoUserDetailsService;

/**
 * Created by yel on 4/26/16.
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  @Qualifier("coUserDetailsService")
  UserDetailsService coUserDetailsService;


  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder authManaBuilder) throws Exception {
/*    authManaBuilder
        .inMemoryAuthentication()
        .withUser("user").password("password").roles("USER");*/
    authManaBuilder
        .userDetailsService(coUserDetailsService).passwordEncoder(passwordEncoder());
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
//        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
        //.antMatchers("/user/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
        .antMatchers("/user/**").access("hasRole('ROLE_USER')")
        .and().formLogin().loginPage("/login").permitAll()

        /*.and().logout()
        .permitAll()*/;
    http.csrf().disable();

  }

  @Bean
  public PasswordEncoder passwordEncoder(){
    PasswordEncoder encoder = new BCryptPasswordEncoder();
    return encoder;
  }

}
